package com.zkt.club.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.zkt.club.gateway.entity.AuthPermission;
import com.zkt.club.gateway.entity.AuthRole;
import com.zkt.club.gateway.redis.RedisUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/21 21:58
 * @description 自定义权限验证接口扩展
 **/

@Component
public class StpInterfaceImpl implements StpInterface {
	
	@Resource
	private RedisUtil redisUtil;
	
	private final String AUTH_PERMISSION_PREFIX = "auth:permission";
	private final String AUTH_ROLE_PREFIX = "auth:role";
	
	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		return getAuth(AUTH_PERMISSION_PREFIX, loginId);
	}
	
	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		return getAuth(AUTH_ROLE_PREFIX, loginId);
	}
	
	@SneakyThrows
	private List<String> getAuth(String prefix, Object loginId) {
		String authKey = redisUtil.buildKey(prefix, loginId.toString());
		
		List<String> authList = new LinkedList<>();
		if (AUTH_ROLE_PREFIX.equals(prefix)) {
			List<AuthRole> roleList = redisUtil.getList(authKey, AuthRole.class);
			authList = roleList.stream().map(AuthRole::getRoleKey).toList();
		} else if (AUTH_PERMISSION_PREFIX.equals(prefix)) {
			List<AuthPermission> permissionList = redisUtil.getList(authKey, AuthPermission.class);
			authList = permissionList.stream().map(AuthPermission::getPermissionKey).toList();
		}
		
		return authList;
	}
}
